package lz77;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		// Get file
		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream("resources/text2.txt")));
		StringBuffer content = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null)
			content.append(line);
		String message = content.toString();

		System.out.println("Text: " + message.length() + " characters.");

		LZ77 lz77 = new LZ77();
		List<LZ77Tupel> list = lz77.compress(message);
		System.out.println("Compressed: " + list.size() + " tupels.");
		System.out.println(lz77.decompress(list));

		String file = "resources/result.lz77";
		save(list, file);
		list = read(file);
		System.out.println(lz77.decompress(list));
	}

	public static void save(List<LZ77Tupel> list, String file) {
		try {
			DataOutputStream stream = new DataOutputStream(
					new FileOutputStream(file));
			for (LZ77Tupel t : list) {
				if (t.getLength() != 0) {
					stream.writeInt(t.getIndex());
					stream.writeInt(t.getLength());
				}
				else
					stream.writeInt(999);
				
				stream.writeChar(t.getChar());
			}
			stream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static List<LZ77Tupel> read(String file) throws Exception {
		DataInputStream stream = new DataInputStream(new FileInputStream(file));
		List<LZ77Tupel> list = new ArrayList<LZ77Tupel>();
		int index;
		int length;
		char c;
		while (stream.available() > 0) {
			index = stream.readInt();
			if (index == 999) {	// is 0,0
				index = 0;
				length = 0;
			}
			else {
				length = stream.readInt();
			}
			c = stream.readChar();
			list.add(new LZ77Tupel(index, length, c));
		}
		stream.close();
		return list;
	}

}
